
//  XHHomeViewController.m
//  xinhua_sx
//
//  Created by 党阳阳 on 14-5-24.
//  Copyright (c) 2014年 broadwave.com. All rights reserved.
//
#import "XHAppDelegate.h"
extern NSString* const kCTSMSMessageReceivedNotification;
extern NSString* const kCTSMSMessageReplaceReceivedNotification;
extern NSString* const kCTSIMSupportSIMStatusNotInserted;
extern NSString* const kCTSIMSupportSIMStatusReady;

id CTTelephonyCenterGetDefault(void);
void CTTelephonyCenterAddObserver(id,id,CFNotificationCallback,NSString*,void*,int);
void CTTelephonyCenterRemoveObserver(id,id,NSString*,void*);
int CTSMSMessageGetUnreadCount(void);

int CTSMSMessageGetRecordIdentifier(void * msg);
NSString * CTSIMSupportGetSIMStatus();
NSString * CTSIMSupportCopyMobileSubscriberIdentity();

id  CTSMSMessageCreate(void* unknow/*always 0*/,NSString* number,NSString* text);
void * CTSMSMessageCreateReply(void* unknow/*always 0*/,void * forwardTo,NSString* text);

void* CTSMSMessageSend(id server,id msg);

NSString *CTSMSMessageCopyAddress(void *, void *);
NSString *CTSMSMessageCopyText(void *, void *);
#define kIOS_VERSION [[UIDevice currentDevice].systemVersion floatValue]
#define WRITH  dispatch_queue_create("com.dispatch.writedb", DISPATCH_QUEUE_SERIAL)
#import "XHHomeViewController.h"
#import "NewsDetailViewController.h"
#import "XHzhangShangViewController.h"
#import "XHHuiMinViewController.h"
#import "XHHomeViewModel.h"
#import "XHDynamicNewsViewController.h"
#import "XHInterActiveViewController.h"
#import "dangeViewController.h"
#import "wangshiViewController.h"
#import "MainEnterViewController.h"
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MKReverseGeocoder.h>
#import <MapKit/MKPlacemark.h>
#import "Reachability.h" 
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import "AFNetworking.h"
#import <CoreTelephony/CTCarrier.h>
@interface XHHomeViewController ()<CLLocationManagerDelegate>
@property (nonatomic ,strong) XHHomeViewModel *viewmodel;

@property (nonatomic, strong) XHArticleNewsView* x1;
@end

@implementation XHHomeViewController
@synthesize webView = _webView;//版本更新;
@synthesize x1= _x1;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        CGRect rect = [[UIScreen mainScreen] bounds];
       
        self.view.frame = rect;
        self.view.backgroundColor = [UIColor whiteColor];
        CGFloat oY = kIOS_VERSION<7.0?44:64;
        
        UIScrollView *view = [[UIScrollView alloc] initWithFrame:CGRectMake(0,oY, rect.size.width, rect.size.height-oY)];
        view.bounces = NO;
//        view.backgroundColor = [UIColor blueColor];
        
        //添加 图片新闻 热点新闻 和 按钮
        NewsScrollView *newsScrollView = [[NewsScrollView alloc] initWithFrame:CGRectMake(0, -20,rect.size.width, 160+20)];
        newsScrollView.delegate = self;
        [view addSubview:newsScrollView];
    
        XHArticleNewsView *articleView = [[XHArticleNewsView alloc] initWithFrame:CGRectMake(5, newsScrollView.frame.origin.y+newsScrollView.frame.size.height+5, rect.size.width-10, 115)];
        _x1 = articleView;
        articleView.delegate = self;
        articleView.layer.borderColor = [XHHomeViewController colorWithHexString:@"#DCDCDC"].CGColor;
        articleView.layer.borderWidth = 1.0f;
        articleView.backgroundColor = [UIColor whiteColor];
        [view addSubview:articleView];
        UIImageView* imageView = [[UIImageView alloc] initWithFrame:CGRectMake(2, newsScrollView.frame.origin.y+newsScrollView.frame.size.height+130, 315, 50)];
        imageView.image = [UIImage imageNamed:@"home_china(1).png"];
        imageView.contentMode = UIViewContentModeScaleToFill;
        UITapGestureRecognizer *tap;
        tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapLoginButton)];
        [imageView setUserInteractionEnabled:YES];
        [imageView addGestureRecognizer:tap];
        [view addSubview:imageView];
       
        UIView *buttonView = [[[NSBundle mainBundle]loadNibNamed:@"ButtonView" owner:self options:nil] objectAtIndex:0];
        
        
        [buttonView setFrame:CGRectMake(0,articleView.frame.origin.y+articleView.frame.size.height+60, rect.size.width, 200)];
        [view addSubview:buttonView];
        
        CGFloat height = buttonView.frame.origin.y+ buttonView.frame.size.height;
        if (height>view.frame.size.height) {
            view.contentSize = CGSizeMake(320, height);
            
        }
    
        [self.view addSubview:view];
        
        self.viewmodel = [[XHHomeViewModel alloc] init];
       // [self.viewmodel getAllCategory];
        UIWebView* webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 320)];//版本更新
        webView.delegate = self;
        self.webView = webView;
       // [self.view addSubview:webView];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^void (void) {
            //showNetworkActivityIndicator();
            // [self onCheckVersion1];
            //[self loadCHee];
        });
    }
    [self.view bringSubviewToFront:self.navBar];
    return self;
}
-(void)viewWillAppear:(BOOL)animated
{
    [_x1 reloadData2];
}
-(void)loadCHee
{
  
    NSString* https = [NSString stringWithFormat:@"http://183.203.18.45:7001/jeesite/version/%@.plist",URLEND];
    id json = [NSDictionary dictionaryWithContentsOfURL:[NSURL URLWithString:https]];
    [self performSelectorOnMainThread:@selector(tishi:) withObject:json waitUntilDone:YES];
  
}
-(void)tishi:(id)json
{
    //NSLog(@"sender = %@",sender);
    if (json != nil)
    {
        
        NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
        NSString *currentVersion = [infoDic objectForKey:@"CFBundleVersion"];
        
        NSLog(@"cur = %@",currentVersion);
        if (![json[@"items"][0][@"metadata"][@"bundle-version"] isEqualToString:currentVersion] && [json[@"items"][0][@"metadata"][@"bundle-version"] length]>0) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"更新" message:@"有新的版本更新，是否前往更新？" delegate:self cancelButtonTitle:@"关闭" otherButtonTitles:@"更新", nil];
            alert.tag = 90002;
            [alert show];
        }
        else
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"更新" message:@"此版本为最新版本" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            alert.tag = 90001;
           // [alert show];
        }
        
        NSLog(@"json = %@",json[@"items"][0][@"metadata"][@"bundle-version"]);
    }
    else
    {
        
        NSLog(@"error");
    }

}
//版本更新
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
    NSString *js = @"document.getElementById('version').innerHTML";
    NSString *pageSource = [webView stringByEvaluatingJavaScriptFromString:js];
    NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
    NSString *currentVersion = [infoDic objectForKey:@"CFBundleVersion"];
    NSLog(@"当前版本= %@ ，服务器版本= %@",currentVersion,pageSource);
    if (![pageSource isEqualToString:currentVersion] && [pageSource length]>0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"更新" message:@"有新的版本更新，是否前往更新？" delegate:self cancelButtonTitle:@"关闭" otherButtonTitles:@"更新", nil];
        alert.tag = 90002;
        [alert show];
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"更新" message:@"此版本为最新版本" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        alert.tag = 90001;
        // [alert show];
    }
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 90002)
    {
        if (buttonIndex==1) {
            // NSURL *url = [NSURL URLWithString:@"https://itunes.apple.com/cn/app/id834207906"];
            //[[UIApplication sharedApplication]openURL:url];
                        NSString *u=[NSString stringWithFormat:@"http://www.xhsx.org:7001/jeesite/version/%@.html",URLEND];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:u]];//复制时替换成  发布的地址
            
        }
        
    }
}
+ (UIColor *) colorWithHexString: (NSString *)color
{
    NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    // String should be 6 or 8 characters
    if ([cString length] < 6) {
        return [UIColor clearColor];
    }
    
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"])
        cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
        return [UIColor clearColor];
    
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    
    //r
    NSString *rString = [cString substringWithRange:range];
    
    //g
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    
    //b
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
}
-(void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)tapLoginButton
{
    NSLog(@"tap");
    wangshiViewController* view = [[wangshiViewController alloc] init];
    view.string1 = @"新华社发布";
    [self.navigationController pushViewController:view animated:YES];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
     BOOL fitrst = [[NSUserDefaults standardUserDefaults] boolForKey:@"firstStart1"];
    if (!fitrst)
    {
        [self iphonefff];
    }
    [self loaddishi];//load code;
 
    
   

}
- (BOOL) IsEnableWIFI{
    return([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable);
}
-(void)iphonefff
{
    NSString* gps;
    if (([CLLocationManager locationServicesEnabled]) && ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorized)) {
        NSLog(@"手机gps定位已经开启");
        gps = @"1";
    } else {
        NSLog(@"手机gps定位未开启");
        gps =  @"0";
    }
    NSString* wifi;
    NSString* ip;
    if ([self IsEnableWIFI])
    {
        wifi = @"1";
        ip= @"192.168.1.1";
    }
    else
    {
        wifi = @"0";
        ip = @"";
    }
    CTTelephonyNetworkInfo*  networkInfo = [[CTTelephonyNetworkInfo alloc] init];
    CTCarrier *carrier = networkInfo.subscriberCellularProvider;
    NSString* name = [NSString stringWithFormat:@"%@",carrier.carrierName];
    NSString* number = [NSString stringWithFormat:@"%@",carrier.mobileNetworkCode];
    ;
    NSString* sim;
    if ([CTSIMSupportGetSIMStatus() isEqualToString:kCTSIMSupportSIMStatusNotInserted])
    {
        sim = @"0";
    }
    else
        sim = @"1";
    NSString* equipmentId = [self generateUuidString];
    NSString* writableyes = @"1";
    NSString* OSVersion = [NSString stringWithFormat:@"%f",[[[UIDevice currentDevice] systemVersion] floatValue]];
    NSString* APIVersion = @"";
   // NSString* identifierNumber = [[UIDevice currentDevice] uniqueIdentifier];
    //NSLog(@"手机序列号: %@",identifierNumber);
    //手机别名： 用户定义的名称
    NSString* userPhoneName = [[UIDevice currentDevice] name];
    NSLog(@"手机别名: %@", userPhoneName);
    //设备名称
    NSString* deviceName = [[UIDevice currentDevice] systemName];
    NSLog(@"设备名称: %@",deviceName );
    //手机系统版本
    NSString* phoneVersion = [[UIDevice currentDevice] systemVersion];
    NSLog(@"手机系统版本: %@", phoneVersion);
    //手机型号
    NSString* phoneModel = [[UIDevice currentDevice] model];
    NSLog(@"手机型号: %@",phoneModel );
    //地方型号  （国际化区域名称）
    NSString* localPhoneModel = [[UIDevice currentDevice] localizedModel];
    NSLog(@"国际化区域名称: %@",localPhoneModel );
    
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    // 当前应用名称
    NSString *appCurName = [infoDictionary objectForKey:@"CFBundleDisplayName"];
    NSLog(@"当前应用名称：%@",appCurName);
    // 当前应用软件版本  比如：1.0.1
    NSString *appCurVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    NSLog(@"当前应用软件版本:%@",appCurVersion);
    // 当前应用版本号码   int类型
    NSString *appCurVersionNum = [infoDictionary objectForKey:@"CFBundleVersion"];
    NSLog(@"当前应用版本号码：%@",appCurVersionNum);
     XHAppDelegate *appDele = (XHAppDelegate*)[[UIApplication sharedApplication]delegate];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
    NSString* sting = [NSString stringWithFormat:@"%s/xinhua/m/phoneInformation",HTTP];
    CGRect rect = [[UIScreen mainScreen] bounds];
    NSString* width = [NSString stringWithFormat:@"%d",(NSInteger)rect.size.width];
    NSString* height = [NSString stringWithFormat:@"%d",(NSInteger)rect.size.height];
    
    NSDictionary* dic = @{@"width": width,@"height":height,@"writableyes":writableyes,@"gps":gps,@"wifi":wifi,@"sim":sim,@"name":name,@"number":number,@"iccid":@"",@"headingCode":@"",@"equipmentId":equipmentId,@"OSVersion":phoneVersion,@"APIVersion":@"",@"phoneModel":phoneModel,@"phoneBand":@"IPHONE",@"versionNumber":appCurVersion,@"versionName":appCurName,@"serialNumber":@"",@"networkType":@"",@"IP":ip,@"code":COUTURYCODE,@"mobileOS":@"01",@"appStoreID":@"001",@"longitude":appDele.lg,@"latitude":appDele.la,@"mobilePhoneNumber":@""};
    [manager POST:sting parameters:dic success:^(AFHTTPRequestOperation*operation, id responseObject) {
        id jsonObject = [NSJSONSerialization JSONObjectWithData:operation.responseData
                                                        options:NSJSONReadingAllowFragments
                                                          error:nil];
        NSLog(@"json1111111 = %@",jsonObject);
        NSLog(@"result = %@",jsonObject[@"message"]);
        NSLog(@"result = %@",jsonObject[@"result"]);
        if ([jsonObject[@"result"] isEqualToString:@"success"])
        {
            NSLog(@"yes");
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstStart1"];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError*error) {
        NSLog(@"error2 = %@",error);
    }];

  
}

- (NSString *)generateUuidString//UUID
{
    
    CFUUIDRef uuid = CFUUIDCreate(kCFAllocatorDefault);
    NSString *uuidString = (NSString*)CFBridgingRelease(CFUUIDCreateString(kCFAllocatorDefault, uuid));
    
    CFRelease(uuid);
    
    return uuidString;
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



- (IBAction)selectButton:(id)sender
{
    butoncl* al = [[butoncl alloc] init];
    [al postString:@"001"fff:@""];
    if ([sender isKindOfClass:[UIButton class]]) {
        XHBasicViewController *viewController;
        MainEnterViewController* v1 = [[MainEnterViewController alloc] init];
        NSDictionary* dic = @{@"childList": @[@{@"id": @"38",@"name":@"舆情快报"},@{@"id":@"39",@"name":@"半月舆情动态"},@{@"id":@"40",@"name":@"分析报告"}]};
        v1.yinitData = dic;
        v1.damokuai = @"舆情快报";
        UIButton *button = (UIButton *)sender;
        if (button.tag == 1000)
        {
            NSString* UID = [[NSUserDefaults standardUserDefaults] objectForKey:@"UID"];
            if (!UID)
            {
                UIAlertView* view = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请先登录" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
                [view show];
                return;
            }
        }
        switch (button.tag) {
            case 1000:
               
            
                [self.navigationController pushViewController:v1 animated:YES];
                return;
                //break;
            case 1001:
                viewController = [[XHDynamicNewsViewController alloc] init];
                break;
            case 1002:
                viewController = [[XHzhangShangViewController alloc]init];
                
                break;
            case 1003:
                viewController = [[XHHuiMinViewController alloc] init];
                break;
            case 1004:
                viewController = [[XHInterActiveViewController alloc] init];
                
                break;
            default:
                break;
        }
        [self.navigationController pushViewController:viewController animated:YES];
    }

}

-(void)loaddishi
{
    NSUserDefaults* des = [NSUserDefaults standardUserDefaults];
    NSDate *  senddate=[NSDate date];
    
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    
    [dateformatter setDateFormat:@"YYYYMMddHHmmss"];
    NSString*  nowtime=[dateformatter stringFromDate:senddate];
    
    id oldDate;
    oldDate = [des objectForKey:@"oldData"];
    NSLog(@"old  = %@  now = %@",[dateformatter stringFromDate:oldDate],nowtime);
    NSTimeInterval time = [[des objectForKey:@"oldData"] timeIntervalSinceNow];
    NSLog(@"time:%d",abs(time)/60/60/24);
   // NSLog(@"a = %@",[des objectForKey:@"allcode"]);
    if (abs(time)/60/60/24 == 0)
    {
        return;
    }
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
    
    
    NSString* sting = [NSString stringWithFormat:@"http://183.203.18.45:7001/xinhua/m/areaList-15.html"];
    
    [manager GET:sting parameters:nil success:^(AFHTTPRequestOperation*operation, id responseObject) {
        id jsonObject = [NSJSONSerialization JSONObjectWithData:operation.responseData
                                                        options:NSJSONReadingAllowFragments
                                                          error:nil];
        NSLog(@"json = %@",jsonObject);
        NSLog(@"JSON CLASS = %@",[jsonObject class]);
        NSLog(@"json count = %d",[jsonObject count]);
        if ([[jsonObject class] isSubclassOfClass:[NSArray class]] && [jsonObject count] > 0)
        {
            [des setObject:jsonObject forKey:@"allcode"];
          
            NSLog(@"nowtime = %@",nowtime);
            [des setObject:senddate forKey:@"oldData"];
            [des synchronize];
            NSLog(@"code 保存成功！");
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError*error) {
        NSLog(@"error = %@",error);
    }];
    
}

-(void)pusdhyaowen1
{
    dangeViewController * viu = [[dangeViewController alloc] init];
    viu.titleString =@"本地新闻";
    [self.navigationController pushViewController:viu animated:YES];
}
-(void)pusdhyaowen
{
    dangeViewController * viu = [[dangeViewController alloc] init];
    viu.titleString =@"要闻推荐";
    [self.navigationController pushViewController:viu animated:YES];
}
- (void)selectArticleWithNewsId:(id)newsId withImageString:(NSString *)imageString
{   
    [self pushNewsDetailViewControllerWithNewsId:newsId withImageString:imageString];
    
}
- (void)selectNewsScrollViewCellForId:(id)newsId withImageString:(NSString *)imageString
{
    [self pushNewsDetailViewControllerWithNewsId:newsId withImageString:imageString];
}



- (void)stillPushWhenSelectFirstCell
{

}


- (void)pushNewsDetailViewControllerWithNewsId:(id)newsId withImageString:(NSString*)imageString
{
    NewsDetailViewController *newsDetailViewController = [[NewsDetailViewController alloc] initWithNewsId:newsId];
    newsDetailViewController.imageString = imageString;
    [self.navigationController pushViewController:newsDetailViewController animated:YES];
    
}
@end

